package webgamemaker.Editor;

import java.util.Date;
import java.util.Iterator;

import webgamemaker.Common.Callback;
import webgamemaker.RPGMakerVXLoader.Marshal;
import webgamemaker.RPGMakerVXLoader.RPGMakerVXLoader;
import webgamemaker.RPGMakerVXLoader.Marshal.MarshalValueObject;
import webgamemaker.RPGMakerVXLoader.Marshal.MarshalValueUserDef;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.xhr.client.ReadyStateChangeHandler;
import com.google.gwt.xhr.client.XMLHttpRequest;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.types.SelectionType;
import com.smartgwt.client.widgets.events.IconClickEvent;
import com.smartgwt.client.widgets.events.IconClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.menu.IMenuButton;
import com.smartgwt.client.widgets.menu.Menu;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;



public class Editor implements EntryPoint {
	
	public TileSetPanel tilesetPanel;
	public MainPanel mainPanel;
	public VLayout topLayout;
	public Toolbar toolbar;
	public HLayout menuBar;
	public Menu fileMenu, editMenu, helpMenu;
	public ProjectTree projectTree;
	public ProjectManager projectManager;

	public native void BinaryReader(String url) /*-{
		var req = new XMLHttpRequest();

		req.open('GET', url, false);

		//XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com] 
		req.overrideMimeType('text/plain; charset=x-user-defined');
		
		req.send(null);

		if (req.status != 200) throwException(_exception.FileLoadFailed);

		fileContents = req.responseText;

		fileSize = fileContents.length;

		alert(fileContents.charCodeAt(163) & 0xff);
		//this.readByteAt = function(i){
			//return fileContents.charCodeAt(i) & 0xff;
		//}
	}-*/;
	
	public native void overrideMimeType(XMLHttpRequest req, String val)/*-{
		req.overrideMimeType(val);
	}-*/;
	
	public void printBloc(String str)
	{
		System.out.print(str);
		for(int i=0;i<15-str.length();i++)
			System.out.print(" ");
		System.out.print("|");
	}
	public void readTable(Object array[])
	{
		int width = ((Byte)array[4]&255) | ((Byte)array[5]&255)<<8 | ((Byte)array[6]&255)<<16 | ((Byte)array[7]&255)<<24; 
		int height = ((Byte)array[8]&255) | ((Byte)array[9]&255)<<8 | ((Byte)array[10]&255)<<16 | ((Byte)array[11]&255)<<24; 
		System.out.println("size : ("+width+", "+height+")");
		for(int j=0; j<height; j++)
		{
			for(int i=0; i<width; i++)
			{
				int id1 = 20+i*2+j*2*width;
				int id2 = id1+2*width*height;
				int id3 = id2+2*width*height;
				printBloc(""+((Byte)array[id1]&255)+" "+((Byte)array[id1+1]&255)+" "+((Byte)array[id2]&255)+" "+((Byte)array[id2+1]&255)+" "+((Byte)array[id3]&255)+" "+((Byte)array[id3+1]&255));
			}
			System.out.println("");
		}
	}
	
	class ChangeHandler implements ReadyStateChangeHandler
	{
		public ChangeHandler()
		{
		}
		public void onReadyStateChange(XMLHttpRequest xhr){
			if(xhr.getReadyState() == 4)
			{
				int size = xhr.getResponseText().length();
				byte array[] = new byte[size];
				for(int i=0;i<size;i++)
					array[i] = (byte)getCharCode(xhr,i);
				try {
					MarshalValueObject root = (MarshalValueObject)Marshal.decode(array);
					MarshalValueObject BGM = (MarshalValueObject)((MarshalValueObject)root).get_value("@bgm");
					Iterator<String> it = root.value.keySet().iterator();
					while(it.hasNext())
						System.out.println(it.next());
					MarshalValueUserDef table = (MarshalValueUserDef)root.get_value("@data");
					/*System.out.print("0 : ");
					for(int i=0;i<table.value.size();i++)
					{
						System.out.print((((int)table.get_value(i))&255)+" ");
						if(i%100 == 74)
							System.out.print("\n"+(i+1)+" : ");
					}*/
					Object tab[] = table.value.toArray();
					readTable(tab);
				} catch (Marshal.MarshalException e) {
					e.printStackTrace();
				}
			}
		};
		
		public native int getCharCode(XMLHttpRequest xhr, int id)/*-{
			return xhr.responseText.charCodeAt(id) & 0xff;
		}-*/;
	}

	public void onModuleLoad() {
		try {
			
		projectManager = ProjectManager.getInstance();
		projectManager.data.rootDir = "../data";
		ServerIO.getInstance().setPhpDir("../php");
		
		VLayout vlayout = new VLayout();
		//SplitLayoutPanel p = new MySplitLayoutPanel();
	    
		topLayout = new VLayout();
		menuBar = new HLayout();
		fileMenu = new Menu();
		editMenu = new Menu();
		helpMenu = new Menu();
		menuBar.setMembers(new IMenuButton("File", fileMenu),new IMenuButton("Edit", editMenu),new IMenuButton("Help", helpMenu));
		toolbar = new Toolbar();
		topLayout.setMembers(menuBar, toolbar);
		topLayout.setShowResizeBar(true);
		topLayout.setHeight("20%");
		HLayout hlayout = new HLayout();
		mainPanel = new MainPanel();
		mainPanel.setShowResizeBar(true);
		//final Canvas mapCanvas = new Canvas();
		//mapCanvas.setOverflow(Overflow.AUTO);
		//mapCanvas.setShowResizeBar(true);
		tilesetPanel = new TileSetPanel();
		tilesetPanel.setShowResizeBar(true);
		tilesetPanel.setWidth("30%");
		projectTree = new ProjectTree();
		projectTree.setWidth("20%");
		projectTree.setShowResizeBar(true);
		projectTree.setOverflow(Overflow.AUTO);
		HLayout hlayout2 = new HLayout();
		hlayout2.setMembers(mainPanel, projectTree);
		hlayout.setMembers(tilesetPanel,hlayout2);
		vlayout.setMembers(topLayout,hlayout);
		vlayout.setSize("100%", "100%");
	    vlayout.draw(); 
	    
	    projectManager.setProjectTree(projectTree);
	    projectManager.setTileSetPanel(tilesetPanel);
	    projectManager.setMainPanel(mainPanel);
	    projectManager.setToolbar(toolbar);
	    
	    tilesetPanel.addSelectCallback(new Callback()
		{
			public void onCall(Object src) 
			{
				TileSetPicker tilesetPicker = (TileSetPicker)src;
				mainPanel.setCursorSize(tilesetPicker.selectX2-tilesetPicker.selectX1+1, tilesetPicker.selectY2-tilesetPicker.selectY1+1);
			}
		});
		
	    final RPGMakerVXLoader loader = new RPGMakerVXLoader("../data/Map009.rvdata?cache_breaker="+(new Date().getTime()));
	    loader.addLoadCallback(new Callback()
	    	{
				public void onCall(Object src) 
				{
					loader.mapData.name = "Map009";
					projectManager.addMap(loader.mapData);
					
					System.out.println("loaded");
					//mainPanel.addMap(map);
					/*tilesetPanel.addSelectCallback(new Callback()
						{
							public void onCall(Object src) 
							{
								TileSetPicker tilesetPicker = (TileSetPicker)src;
								gameMap.cursorWidth = tilesetPicker.selectX2-tilesetPicker.selectX1+1;
								gameMap.cursorHeight = tilesetPicker.selectY2-tilesetPicker.selectY1+1;
							}
						});
					loader.gameMap.addSelectCallback(new Callback()
					{
						public void onCall(Object src) 
						{
							TileSetPicker tilesetPicker = tilesetPanel.selectedTileSetPicker;
							final GameMap gameMap = loader.gameMap;
							final int id[] = new int[gameMap.cursorWidth * gameMap.cursorHeight];
							final Tile oldTile[] = new Tile[gameMap.cursorWidth * gameMap.cursorHeight];
							final Tile newTile[] = new Tile[gameMap.cursorWidth * gameMap.cursorHeight];
							for(int i = 0; i < gameMap.cursorWidth; i++)
								for(int j = 0; j < gameMap.cursorHeight; j++)
								{
									id[i+j*gameMap.cursorWidth] = gameMap.cursorX+i+(gameMap.cursorY+j)*gameMap.width;
									oldTile[i+j*gameMap.cursorWidth] = gameMap.tiles[id[i+j*gameMap.cursorWidth]][0];
									newTile[i+j*gameMap.cursorWidth] = tilesetPicker.tileset.tiles.get(tilesetPicker.selectX1+i+(tilesetPicker.selectY1+j)*tilesetPicker.nbTilePerLine);
								}
							projectManager.data.historyManager.makeAction(new HistoryAction()
								{
									public void redo() 
									{
										for(int i = 0; i < id.length; i++)
											gameMap.tiles[id[i]][0] = newTile[i];
										gameMap.redraw();
									}
									public void undo() 
									{
										for(int i = 0; i < id.length; i++)
											gameMap.tiles[id[i]][0] = oldTile[i];
										gameMap.redraw();
									}
								
								});
						}
					});*/
				}
			}); 
	    
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
